package cn.itcast.solr;

import cn.itcast.solr.pojo.Item;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.junit.Test;

import javax.management.Query;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class SolrJSuper {

    @Test
    public void testSort() throws SolrServerException {
        HttpSolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr/core2");

        SolrQuery query = new SolrQuery("*:*");
        query.setSort("price", SolrQuery.ORDER.desc);
        QueryResponse response = solrServer.query(query);
        System.out.println("一共命中" + response.getResults().getNumFound() + "条");

        List<Item> items = response.getBeans(Item.class);
        items.forEach(item -> System.out.println(item));
    }

    @Test
    public void testPage() throws SolrServerException {

        Integer page = 2;
        Integer rows = 2;

        HttpSolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr/core2");

        SolrQuery query = new SolrQuery("*:*");
        query.setSort("price", SolrQuery.ORDER.desc);
        query.setStart((page-1)*rows);
        query.setRows(rows);
        QueryResponse response = solrServer.query(query);
        System.out.println("一共命中" + response.getResults().getNumFound() + "条");

        List<Item> items = response.getBeans(Item.class);
        items.forEach(item -> System.out.println(item));

    }

    @Test
    public void testHL() throws SolrServerException {

        HttpSolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr/core2");

        SolrQuery query = new SolrQuery("title:手机");
        query.setHighlight(true);
        query.addHighlightField("title");
        query.setHighlightSimplePre("<em>");
        query.setHighlightSimplePost("</em>");
        QueryResponse response = solrServer.query(query);

        System.out.println("一共命中" + response.getResults().getNumFound() + "条");
        List<Item> items = response.getBeans(Item.class);

        // 获取高亮结果集
        // 外层Map：key-高亮结果集的id value-又是高亮字段map
        // 内层map：key-高亮字段名 value-高亮结果集
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
        items.forEach(item -> {
            System.out.println("id: " + item.getId());
            System.out.println("price: " + item.getPrice());
            Map<String, List<String>> map = highlighting.get(item.getId());
            System.out.println("高亮的TItle：" + map.get("title").get(0));
        });
    }
}
